const http = require('http');
const fs = require('fs');
const path = require('path');
const multer = require('multer');

// 定义静态资源目录
const publicDir = path.join(__dirname, 'public');
const videoDir = path.join(publicDir, 'videos');
const videosFilePath = path.join(__dirname, 'videos.json');

// 创建视频目录（如果不存在）
if (!fs.existsSync(videoDir)) {
    fs.mkdirSync(videoDir);
}

// 从 videos.json 文件读取视频数据
let videos = [];
try {
    const data = fs.readFileSync(videosFilePath, 'utf8');
    videos = JSON.parse(data);
} catch (err) {
    console.error('读取 videos.json 文件出错:', err);
}

// 配置 multer 中间件
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, videoDir);
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, uniqueSuffix + path.extname(file.originalname));
    }
});

const upload = multer({ storage: storage });

// 将视频数据保存到 videos.json 文件
function saveVideosToFile() {
    fs.writeFile(videosFilePath, JSON.stringify(videos, null, 2), 'utf8', (err) => {
        if (err) {
            console.error('保存 videos.json 文件出错:', err);
        }
    });
}

// 创建 HTTP 服务器
const server = http.createServer((req, res) => {
    const parsedUrl = new URL(req.url, `http://${req.headers.host}`);
    const pathname = parsedUrl.pathname;
    const category = parsedUrl.searchParams.get('category');
    const searchQuery = parsedUrl.searchParams.get('search');

    if (pathname === '/videos') {
        if (category) {
            let filteredVideos;
            if (category === 'all') {
                filteredVideos = videos;
            } else {
                filteredVideos = videos.filter(video => video.category === category);
            }

            if (searchQuery) {
                const lowerCaseQuery = searchQuery.toLowerCase();
                filteredVideos = filteredVideos.filter(video => video.filename.toLowerCase().includes(lowerCaseQuery));
            }

            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify(filteredVideos));
        } else {
            res.writeHead(400, { 'Content-Type': 'text/plain' });
            res.end('缺少分类参数');
        }
    } else if (pathname.startsWith('/videos/')) {
        const videoPath = path.join(publicDir, pathname);
        fs.stat(videoPath, (err, stats) => {
            if (err) {
                res.writeHead(404, { 'Content-Type': 'text/plain' });
                res.end('视频文件未找到');
                return;
            }

            const range = req.headers.range;
            if (!range) {
                res.writeHead(400, { 'Content-Type': 'text/plain' });
                res.end('需要 Range 请求头');
                return;
            }

            const CHUNK_SIZE = 10 ** 6; // 1MB
            const start = Number(range.replace(/\D/g, ''));
            const end = Math.min(start + CHUNK_SIZE, stats.size - 1);
            const contentLength = end - start + 1;
            const headers = {
                'Content-Range': `bytes ${start}-${end}/${stats.size}`,
                'Accept-Ranges': 'bytes',
                'Content-Length': contentLength,
                'Content-Type': path.extname(videoPath) === '.mp4'? 'video/mp4' : path.extname(videoPath) === '.webm'? 'video/webm' : 'video/ogg'
            };
            res.writeHead(206, headers);
            const videoStream = fs.createReadStream(videoPath, { start, end });
            videoStream.pipe(res);
        });
    } else if (pathname === '/upload') {
        upload.single('file')(req, res, (err) => {
            if (err) {
                res.writeHead(500, { 'Content-Type': 'text/plain' });
                res.end('上传出错');
                return;
            }

            const { name, category } = req.body;
            const filename = req.file.filename;

            // 检查文件是否已存在
            const existingVideo = videos.find(video => video.filename === filename);
            if (existingVideo) {
                res.writeHead(200, { 'Content-Type': 'text/plain' });
                res.end('文件已存在，秒传成功');
                return;
            }

            videos.push({ filename, category: category || 'science-fiction' });
            saveVideosToFile();

            res.writeHead(200, { 'Content-Type': 'text/plain' });
            res.end('上传成功');
        });
    } else {
        // 处理静态资源请求
        let filePath = path.join(publicDir, pathname === '/' ? 'index.html' : pathname);

        // 获取文件扩展名
        const extname = path.extname(filePath);
        let contentType = 'text/html';
        switch (extname) {
            case '.js':
                contentType = 'text/javascript';
                break;
            case '.css':
                contentType = 'text/css';
                break;
            case '.json':
                contentType = 'application/json';
                break;
            case '.png':
                contentType = 'image/png';
                break;
            case '.jpg':
                contentType = 'image/jpeg';
                break;
            case '.gif':
                contentType = 'image/gif';
                break;
            case '.mp4':
                contentType = 'video/mp4';
                break;
            case '.webm':
                contentType = 'video/webm';
                break;
            case '.ogg':
                contentType = 'video/ogg';
                break;
        }

        // 读取文件
        fs.readFile(filePath, (err, data) => {
            if (err) {
                res.writeHead(404, { 'Content-Type': 'text/plain' });
                res.end('未找到该资源');
            } else {
                // 文件读取成功，返回文件内容
                res.writeHead(200, { 'Content-Type': contentType });
                res.end(data);
            }
        });
    }
});

// 启动服务器
const port = 3000;
server.listen(port, () => {
    console.log(`服务器正在监听端口 ${port}`);
});    